package network;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class MultiChatClient extends JFrame implements Runnable {
	ServerSocket server = null;
	Socket sock = null;
	MultiChatClient mcc;
	StringBuilder data = new StringBuilder();
	ObjectInputStream receive;
	ObjectOutputStream send;
	MultiChatClientThread mcct;
	HashMap<String, MultiChatClientThread> clients =  new HashMap<String, MultiChatClientThread>();
	DefaultListModel<String> dlm = new DefaultListModel<String>();
	boolean tFlag = true;
	boolean svCon = false;
	
	private JPanel contentPane;
	JButton btnEnd;
	JButton btnStart;
	private JScrollPane scrollPane_1;
	public JComboBox comboBox;
	private JLabel lblNewLabel_1;
	private JTextPane result;
	private JScrollPane scrollPane;
	private JLabel lblNewLabel;
	public JTextField serverIP;
	public JTextField userID;
	public JButton btnWp;
	public JTextField msgIn;
	public JButton btnSend;
	public JList list;
	private JButton btnNewButton;

	
	
	
	
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MultiChatClient frame = new MultiChatClient();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	/**
	 * Create the frame.
	 */
	public MultiChatClient() {
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				if(svCon){
					if(mcct.tFlag)	serverDisconnect();
				}
				
			}
		});
		setTitle("MultiChat Client");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(0, 400, 750, 416);
		contentPane = new JPanel();
		contentPane.setBackground(Color.DARK_GRAY);
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		contentPane.add(getBtnEnd());
		contentPane.add(getBtnStart());
		contentPane.add(getScrollPane_1());
		contentPane.add(getComboBox());
		contentPane.add(getMsgIn());
		contentPane.add(getBtnSend());
		contentPane.add(getScrollPane_2());
		contentPane.add(getTextField_1());
		contentPane.add(getTextField_2());
		contentPane.add(getBtnWp());

		

		try{
			InetAddress ia = InetAddress.getLocalHost(); // 주소를 가져와 타이틀을 IP주소로 변경해준다.			
			setTitle("IP Address: " + ia.getHostAddress() + ", Port Number : 4444");
			serverIP.setText(ia.getHostAddress());
			contentPane.add(getBtnNewButton());
		}catch(Exception ei){
			ei.printStackTrace();
		}

	}

	@Override
	public void run() {	
		try {
			sock = new Socket(serverIP.getText(), 4444);
			mcct = new MultiChatClientThread(this,sock);
			mcct.start();

		} catch (Exception e) {
			//e.printStackTrace();
			JOptionPane.showMessageDialog(null, "서버에 접속 할 수 없습니다.");
			btnStart.setEnabled(true);
			btnEnd.setEnabled(false);
		}
	}
	public void sendMsg(String a){
		try {			
			SocketData sd = new SocketData("message",userID.getText(),a,null);
			mcct.sendMsg(sd);			
			msgIn.setText("");
			msgIn.requestFocus();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void dataSet(String a){
		data.append(a + "<br/>");
		result.setText(data.toString());
	}
	public void dataSet(SocketData a){
		String icon = "";
		if(a.getIndex() > 0){
			icon = "<img src = 'file:\\C:\\workspace\\JavaCore\\src\\imgset\\ori" + a.getIndex() + ".jpg' width='100' height='100'><br/>";
			data.append(icon);			
		}
		data.append(a.getUser() + " : " + a.getMessage() + "<br/>");
		result.setText(data.toString());
		result.setCaretPosition(result.getDocument().getLength()); // 새로운 채팅이 아래로 오도록.
	}	
	
	
	public void serverConnect(){
		svCon=true;
		Thread t = new Thread(this);
		t.start();
		btnStart.setEnabled(false);
		btnEnd.setEnabled(true);	
		btnSend.setEnabled(true);
	}

	public void serverDisconnect(){
		SocketData sd = new SocketData("logout",userID.getText(),"접속을 해제합니다.",null);
		mcct.sendMsg(sd);
		mcct.tFlag=false;
		
		msgIn.setText("");
		msgIn.requestFocus();
		btnStart.setEnabled(true);
		btnEnd.setEnabled(false);
		btnSend.setEnabled(false);		
	}
	
	/*public void serverDisconnect(){//종료
		btn1.setEnabled(true);
		btn2.setEnabled(false);
		btn3.setEnabled(false);
		SimpleDateFormat sdf = new SimpleDateFormat("yy-mm-dd HH:mi");
		String ti = sdf.format(new Date());
		SocketData sd = new SocketData("logout", userID.getText(), " 님이 로그아웃 하셨네요("+ti+")", null);
		mcct.sendMsg(sd);
	}*/

	private JButton getBtnEnd() {
		if (btnEnd == null) {
			btnEnd = new JButton("Chat End");
			btnEnd.setEnabled(false);
			btnEnd.setForeground(Color.WHITE);
			btnEnd.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					serverDisconnect();
				}
			});
			btnEnd.setBackground(Color.DARK_GRAY);
			btnEnd.setBounds(612, 10, 110, 23);
		}
		return btnEnd;
	}
	
	private JButton getBtnStart() {
		if (btnStart == null) {
			btnStart = new JButton("Chat Start");
			btnStart.setForeground(Color.WHITE);
			btnStart.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					serverConnect();
				}
			});
			btnStart.setBackground(Color.DARK_GRAY);
			btnStart.setBounds(490, 10, 110, 23);
		}
		return btnStart;
	}
	
	private JScrollPane getScrollPane_1() {
		if (scrollPane_1 == null) {
			scrollPane_1 = new JScrollPane();
			scrollPane_1.setBounds(235, 43, 487, 275);
			scrollPane_1.setColumnHeaderView(getLblNewLabel_1());
			scrollPane_1.setViewportView(getResult());
		}
		return scrollPane_1;
	}
	
	private JComboBox getComboBox() {
		if (comboBox == null) {
			comboBox = new JComboBox();
			comboBox.setBackground(Color.DARK_GRAY);
			comboBox.setBounds(12, 328, 103, 23);
			
			//콤보박스용 이모티콘 이미지추가		
			comboBox.addItem(new ImageIcon("src/imgset/th0.png"));
			comboBox.addItem(new ImageIcon("src/imgset/th1.png"));
			comboBox.addItem(new ImageIcon("src/imgset/th2.png"));
			comboBox.addItem(new ImageIcon("src/imgset/th3.png"));	
			comboBox.addItem(new ImageIcon("src/imgset/th4.png"));
			comboBox.addItem(new ImageIcon("src/imgset/th5.png"));
			comboBox.addItem(new ImageIcon("src/imgset/th6.png"));		
			comboBox.addItem(new ImageIcon("src/imgset/th7.png"));
			comboBox.addItem(new ImageIcon("src/imgset/th8.png"));	
			
		}
		return comboBox;
	}
	
	private JTextField getMsgIn() {
		if (msgIn == null) {
			msgIn = new JTextField();
			msgIn.setForeground(Color.WHITE);
			msgIn.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent e) {
					int a = e.getKeyCode();
					if(a == e.VK_ENTER){
						sendMsg(msgIn.getText());
					}

				}
			});
			msgIn.setBackground(Color.DARK_GRAY);
			msgIn.setText("Message");
			msgIn.setColumns(10);
			msgIn.setBounds(127, 329, 427, 22);
		}
		return msgIn;
	}
	
	private JButton getBtnSend() {
		if (btnSend == null) {
			btnSend = new JButton("Send");
			btnSend.setForeground(Color.WHITE);
			btnSend.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					sendMsg(msgIn.getText());
				}
			});
			btnSend.setBackground(Color.DARK_GRAY);
			btnSend.setBounds(566, 328, 77, 23);
		}
		return btnSend;
	}
	
	private JLabel getLblNewLabel_1() {
		if (lblNewLabel_1 == null) {
			lblNewLabel_1 = new JLabel("Chat Room");
			lblNewLabel_1.setOpaque(true);
			lblNewLabel_1.setBackground(Color.PINK);
			lblNewLabel_1.setHorizontalAlignment(SwingConstants.CENTER);
		}
		return lblNewLabel_1;
	}
	
	private JTextPane getResult() {
		if (result == null) {
			result = new JTextPane();
			result.setContentType("text/html");
			result.setBackground(Color.PINK);
		}
		return result;
	}
	
	private JScrollPane getScrollPane_2() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setBounds(12, 43, 211, 242);
			scrollPane.setViewportView(getList());
			scrollPane.setColumnHeaderView(getLblNewLabel());
		}
		return scrollPane;
	}
	
	private JList getList() {
		if (list == null) {
			list = new JList(dlm);
			list.setBackground(Color.PINK);
		}
		return list;
	}
	
	private JLabel getLblNewLabel() {
		if (lblNewLabel == null) {
			lblNewLabel = new JLabel("User List");
			lblNewLabel.setOpaque(true);
			lblNewLabel.setBackground(Color.PINK);
			lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
		}
		return lblNewLabel;
	}
	
	private JTextField getTextField_1() {
		if (serverIP == null) {
			serverIP = new JTextField();
			serverIP.setHorizontalAlignment(SwingConstants.CENTER);
			serverIP.setForeground(Color.WHITE);
			serverIP.setBackground(Color.DARK_GRAY);
			serverIP.setText("Server IP Address");
			serverIP.setBounds(12, 11, 338, 22);
			serverIP.setColumns(10);
		}
		return serverIP;
	}
	
	private JTextField getTextField_2() {
		if (userID == null) {
			userID = new JTextField();
			userID.setForeground(Color.WHITE);
			userID.setBackground(Color.DARK_GRAY);
			userID.setText("ID");
			userID.setBounds(362, 11, 116, 21);
			userID.setColumns(10);
		}
		return userID;
	}
	
	private JButton getBtnWp() {
		if (btnWp == null) {
			btnWp = new JButton("Finish Whisper");
			btnWp.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
				}
			});
			btnWp.setForeground(Color.WHITE);
			btnWp.setBackground(Color.DARK_GRAY);
			btnWp.setBounds(12, 295, 211, 23);
		}
		return btnWp;
	}
	private JButton getBtnNewButton() {
		if (btnNewButton == null) {
			btnNewButton = new JButton("File");
			btnNewButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					SocketData sd = new SocketData("fileTrans",userID.getText(),"파일을 전송합니다.",null);
					mcct.sendMsg(sd);					
				}
			});
			
			btnNewButton.setBackground(Color.DARK_GRAY);
			btnNewButton.setForeground(Color.WHITE);
			btnNewButton.setBounds(645, 328, 77, 23);
		}
		return btnNewButton;
	}
}
